import style from './index.module.less'
import front from '@imgs/id-front.png'
import back from '@imgs/id-back.png'
import { AddOutline, CloseOutline } from 'antd-mobile-icons'
import { Toast } from 'antd-mobile'
import { getObjectURL } from '@js/tool'
import { useMemo, useRef } from 'react'

// 改变文件
async function changeFile (e, setFn) {
  const files = e.target.files
  if (!(files instanceof FileList)) {
    return undefined
  }
  if (files.length === 0 || !(files[0] instanceof File)) {
    return undefined
  }
  const file = files[0]
  if (!['image/jpeg', 'image/png', 'image/jpg'].includes(file.type)) {
    Toast.show('请上传格式为png、jpg或jpeg的图片')
    return undefined
  }
  setFn(file)
}


function Main ({ isFront = false, value, onChange }) {
  const ref = useRef()
  const url = useMemo(() => {
    if (!value) {
      return undefined
    }
    if (value instanceof File) {
      return getObjectURL(value)
    }
    return value.url
  }, [value])
  return (
    <div className={style.container}>
      <label className={style.inner}>
        <input ref={ref} type='file' multiple={false} className={style.input} onChange={async e => await changeFile(e, onChange)} />
        <div className={style.mask} />
        <div className={style.bg}>
          <img src={isFront ? front : back} alt='身份证正面' />
          <div className={style.icon}>
            <AddOutline />
          </div>
        </div>
        <div className={style.notice}>
          {isFront ? <span>请上传人像面</span> : <span>请上传国徽面</span>}
        </div>
        {!!url && <img className={style.pic} src={url} alt='' />}
      </label>
      {!!value && (
        <div
          className={style.clear}
          onClick={(e) => {
            e.stopPropagation();
            onChange(undefined);
            ref.current.value = null;
          }}
        >
          <CloseOutline />
        </div>
      )}
    </div>
  )
}

export default Main